package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author wys
 */
@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {

    @Autowired
    private EmpService empService;

    @Override
    public PageResult<Clazz> getPageResult(ClazzQueryParam param) {
        String name = param.getName();
        LocalDate begin = param.getBegin();
        LocalDate end = param.getEnd();
        Page<Clazz> clazzPage = new Page<>(param.getPage(), param.getPageSize());
        LambdaQueryWrapper<Clazz> lambdaQueryWrapper = new LambdaQueryWrapper<Clazz>()
                .eq(StringUtils.isNotBlank(name), Clazz::getName, name)
                .between(!Objects.isNull(begin) && !Objects.isNull(end), Clazz::getEndDate, begin, end);
        page(clazzPage,lambdaQueryWrapper);
        List<Clazz> clazzList = clazzPage.getRecords();
        List<Integer> masterIdList = clazzList.stream().map(Clazz::getMasterId).toList();
        if (!masterIdList.isEmpty()) {
            List<Emp> deptList = empService.listByIds(masterIdList);
            Map<Integer, String> empMap = deptList.stream().collect(Collectors.toMap(Emp::getId, Emp::getName));
            clazzList.forEach(v -> v.setMasterName(empMap.get(v.getMasterId())));
        }
        clazzList.forEach(v->v.setStatus(v.getBeginDate().isAfter(LocalDate.now())?"未开班"
                :v.getEndDate().isBefore(LocalDate.now())?"已结课" :"在读"));
        return new PageResult<>(clazzPage.getTotal(), clazzList);
    }
}
